'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''

from dopplershift.core.conf import XMLFileBasedConfig

class XMLPairConfig(XMLFileBasedConfig):
    def get(self, key, parent_type=None, parent_code=None):
        query = '''%s/pair[@key='%s']/@value'''%(self._subquery(parent_type, parent_code), key)
        
        for el in self._content.xpath(query):
            return unicode(el)
        return None
    def _subquery(self, parent_type, parent_code):
        query ='''//pairs'''
        if parent_type != None or parent_code != None:
            if parent_type != None and parent_code != None:
                query = '''%s[@type='%s' and @code='%s']'''%(query, parent_type, parent_code)
            elif parent_type != None:
                query = '''%s[@type='%s']'''%(query, parent_type)
            elif parent_code != None:
                query = '''%s[@code='%s']'''%(query, parent_type)
        return query
    def get_list(self, parent_type=None, parent_code=None, key=None):
        query = '''%s/pair'''%(self._subquery(parent_type, parent_code))
        
        if not key is None:
            query += """[@key='%s']"""%str(key)
        for el in self._content.xpath(query):
            yield el.get('key'), el.get('value')
    def xpath(self, xpath):
        return self._content.xpath(xpath)